<template>
	<view class="container">
		<view class="swiperBox">
			<!-- 轮播 -->
			<swiper indicator-dots autoplay :indicator-dots="false" class="swiper">
			  <swiper-item v-for="(item, index) in imgList" :key="index">
				<image :src="imgUrl+item"></image>
				<view class="page">
					{{index+1}}/{{length}}
				</view>
			  </swiper-item>
			</swiper>
			<view class="infoBox">
				<view class="info">
					<view class="price">￥{{info.price}}</view>
					<view class="inventory">库存：{{info.inventory}}</view>
				</view>
				<view class="name">{{info.name}}</view>
			</view>
			<view class="content">
				<h3>
					<image src="../../static/img/img/shop.png" mode="" class="iconImg"></image>
					商品详情
				</h3>
				<view class="infoCon" v-html="info.content"></view>
			</view>
		</view>
		<!-- <button class="btn" @click="open">立即购买</button> -->
		<button class="btn" v-if="!token" @click="login_zheshow">
			提交订单
		</button>
		<button class="btn" v-if="token" @click="open">提交订单</button>
		<!-- 购买弹窗 -->
		<uni-popup ref="popup" type="bottom" border-radius="10px 10px 0 0">
			<view class="popup">
				<!-- 关闭窗口 -->
				<view class="gb">
					<image src="../../static/img/colse.png" mode="" class="colse" @click="colse"></image>
				</view>
				<!-- 订单信息 -->
				<view class="shopInfo">
					<view class="shopTop">
						<image :src="imgUrl+imgList[0]" class="img-item" @click="previewImage(0)"/>
						<view class="shopR">
							<view class="shopRName">{{info.name}}</view>
							<view class="shopPrice">
								<view class="priceItem">
									￥{{info.price}}
								</view>
								<view class="shopNum">
									<uni-number-box :min="1" :max="10"  @change="changeValue"/>
								</view>
							</view>
						</view>
					</view>
				</view>
				<!-- 联系人/联系电话/收货地址 -->
				<view class="userInfo">
					<view>
						<form @submit="formSubmit" @reset="formReset">
							<view class="uni-form-item uni-column">
								<view class="title">
									<!-- <image src="../../static/img/name.png" mode="" class="icon"></image> -->
									联系人：
								</view>
								<input class="uni-input" name="userName" v-model="userInfo.userName" placeholder="请输入联系人" />
							</view>
							<view class="uni-form-item uni-column">
								<view class="title">
									<!-- <image src="../../static/img/name.png" mode="" class="icon"></image> -->
									联系方式：
								</view>
								<input class="uni-input" name="phone" v-model="userInfo.phone" placeholder="请输入联系方式" />
							</view>
							<view class="uni-form-item uni-column">
								<view class="title">
									<!-- <image src="../../static/img/name.png" mode="" class="icon"></image> -->
									收货地址：
								</view>
								<input class="uni-input" name="address" v-model="userInfo.address" placeholder="请输入收货地址" />
							</view>
							<view class="uni-form-item uni-column">
								<view class="title">
									优惠券：
								</view>
								<view class="couponBox" @click="handleYhq">
									<view class="coupon">
										<text>{{yhqId}}{{coupon}}</text>
									</view>
								</view>
							</view>
							<view class="uni-form-item uni-column">
								<view class="title">
									备注：
								</view>
								<view class="couponBox">
									<input class="uni-input" name="remark" v-model="userInfo.remark" placeholder="选填" />
								</view>
							</view>
							<view class="uni-btn-v">
								<view class="uniPrice">
									￥{{uniPrice}}
								</view>
								<button form-type="submit" class="gmBtn">立即购买</button>
							</view>
						</form>
					</view>
				</view>
			</view>
		</uni-popup>
		
		<!-- 优惠券弹窗 -->
		<uni-popup ref="yhqpopup" type="bottom" border-radius="10px 10px 0 0">
			<view class="yhqBox">
				<!-- 关闭窗口 -->
				<view class="gb">
					<image src="../../static/img/colse.png" mode="" class="yhqcolse" @click="yhqcolse"></image>
				</view>
				<ul>
					<li class="couponItem" v-for="item in yhqlist">
						<view class="couponPrice">
							￥{{item.yhqPrice}}
						</view>
						<view class="couponInfo">
							<view class="couponTitle">{{item.yhqName}}</view>
							<view>{{item.intro}}</view>
							<view>{{item.startTime | formatDate}} - {{item.endTime | formatDate}}</view>
						</view>
						<view class="couponBtn">
							<view class="couponlod" v-if="item.syzt==0" @click="handleDsy(item.yhqPrice,item.yhqName,item.id)">
								待兑换
							</view>
							<view class="couponlodz" v-if="item.syzt==1">
								正在使用
							</view>
						</view>
					</li>
				</ul>
			</view>
		</uni-popup>
	</view>
</template>

<script>
	import btnlogin from '@/components/butlogin';
	import graceChecker from "../../api/graceChecker.js"
	import { shopDetails,hdList,shopList,userInfo,getPreferential } from '@/api/api.js'
	import config from '@/config'
	import { getPay,getEnrollTran } from '@/api/pay.js'
	import { jfdh,getBuyShop} from '@/api/shop.js'
	export default {
		components:{
			btnlogin
		},
		data() {
			return {
				imgUrl:config.baseUrl,
				ymId:"",
				imgList: [],
				length:"",
				info:{},
				inputValue: '',
				pickerValue: 0,
				coupon:'点击查看优惠券',
				uniPrice:"",
				num:1,
				userInfo:{},
				token:"",
				zheshow:false, // 控制弹窗显示隐藏
				openid:"",
				payInfo:{},
				paymentTrade:"",
				// 优惠券弹窗
				yhqShow:false,
				yhqlist:[],
				yhPrice:"",
				yhqId:"",
			}
		},	
		onLoad(options) {
			this.ymId = options.id
		    this.banner(options.id);
			this.getUser()
		  },
		methods: {
			// 查询banner数据
			banner(id) {
				shopDetails(id).then((res) => {
					if(res.code==200){
						this.imgList = res.data.images.split(",")	
						this.length = this.imgList.length
						this.info = res.data
						this.info.price = this.info.price.replace(/\.00$/, '');
						this.uniPrice = this.info.price.replace(/\.00$/, '');
						console.log('22222222',this.uniPrice)
					}
				  })
			},
			// 获取缓存的电话号码
			getUser(){
				let that = this
				uni.getStorage({
				    key: 'data1',
				    success: function (res) {
						// 查询用户信息表中是否有该手机号
						userInfo(res.data.phone).then((userRes) => {
							that.openid = res.data.openid
							that.token = res.data.token
							that.userInfo = userRes.info
						  })
				    }
				});
			},
			
			// 如果token不存在
			login_zheshow(){					uni.navigateTo({
						url: '../login/login',
					});				},
			// 点击按钮
			open(){
				// 通过组件定义的ref调用uni-popup方法 ,如果传入参数 ，type 属性将失效 ，仅支持 ['top','left','bottom','right','center']
				this.$refs.popup.open('bottom')
				this.getUser();
			},
			
			// 优惠券弹窗
			handleYhq(){
				let data = {					yhqFfId:this.userInfo.id,					switch:1,				}				getPreferential(data).then((res) => {
					if(res.data.length>0){
						this.yhqlist = res.data
						this.$refs.yhqpopup.open('bottom')
						for (let i = 0; i < this.yhqlist.length; i++) {
							this.yhqlist[i].yhqPrice = this.yhqlist[i].yhqPrice.replace(/\.00$/, '');  
						}
						// 判断优惠券id，如果id存在遍历判断使用状态
						if(this.yhqId){
							for (let i = 0; i < this.yhqlist.length; i++) {
								if(this.yhqId==this.yhqlist[i].id){
									this.yhqlist[i].syzt = 1 //正在使用
								}else{
									this.yhqlist[i].syzt = 0  //未使用
								}
							}
						}else{
							for (let i = 0; i < this.yhqlist.length; i++) {
								this.yhqlist[i].syzt = 0//未使用
							}
						}
						
					}else{
						uni.showToast({
							title: '暂无优惠券',
							icon: 'none',
						});
					}				  })
			},
			
			// 待使用按钮
			handleDsy(price,name,id){
				let data = {
					phone:this.userInfo.phone,
					userName:this.userInfo.userName,
					id:id,
					yhqname:name,
					price:price,
				}
				jfdh(data).then((res) => {
					if(res.code==200){
						uni.showToast({
							title: res.message,
							icon: 'success',
						});
						this.uniPrice = this.uniPrice - price
						// 优惠券的价格
						this.yhPrice = price
						this.coupon =  name
						this.yhqId = id
						this.$refs.yhqpopup.close()
					}else{
						uni.showToast({
							title: res.message,
							icon: 'none',
						});
					}
				  })
				
			},
			
			// 立即购买--支付
			getPayment(){
				let that = this
				let temp = {
				  hname:that.info.name,
				  name:that.userInfo.userName,
				  phone:that.userInfo.phone,
				  card:that.userInfo.card,
				  address:that.userInfo.address,
				  price : that.uniPrice,
				  openid:that.openid,
				  payment_type:2,
				  hid:that.info.id,
				};
				// 支付订单
				getPay(temp).then((res) => {
					// 商户号
					that.paymentTrade = res.dataInfo	
					 // 调起支付接口
					 uni.requestPayment({
						provider: "wxpay",
						appid: res.data.appId, // 微信开放平台 - 应用 - AppId，注意和微信小程序、公众号 AppId 可能不一致
						timeStamp: res.data.timeStamp, // 时间戳（单位：秒）
						package: res.data.package, // 固定值
						paySign: res.data.paySign, //签名
						signType: res.data.signType, // 签名算法，这里用的 MD5/RSA 签名
						nonceStr: res.data.nonceStr, // 随机字符串
						success(res) {
							if (res.errMsg == "requestPayment:ok") {
								uni.showToast({
										title: '支付成功',
										icon: 'success',
									});
									// 添加商品交易记录
									temp.type = 1,
									temp.num = that.num,
									temp.remark = that.userInfo.remark,
									getBuyShop(temp).then((res) => {
									})
								setTimeout(() => {
									uni.reLaunch({
										url: '/pages/index/index'
									 });
								  }, 1000);
							}
						},
						fail(e) {
							if (e.errMsg == "requestPayment:fail cancel") {
								uni.showToast({
										title: '取消支付',
										icon: 'none',
									});
							} else {
								uni.showToast({
										title: '取消失败',
										icon: 'error',
									});
									}
								}
							})
				 })
			},
			
			
			// 关闭弹窗
			colse(){
				this.$refs.popup.close()
				this.userInfo = {}
			},
			
			// 关闭优惠券弹窗
			yhqcolse(){
				this.$refs.yhqpopup.close()
			},
			
			// 图片轮播
			previewImage(index){
				let listData = []
				for (let i = 0; i < this.imgList.length; i++) {
					listData.push(this.imgUrl+this.imgList[i]);
				}
				 uni.previewImage({
					current: index, // 当前显示图片索引
					urls: listData, // 需要预览的图片 URL 列表
					success: () => {
					  // 成功回调，可以不处理
					},
					fail: () => {
					  // 失败回调，可以不处理
					},
				  });
			},
			// 根据数量的变化计算价格
			changeValue(value){
				this.num = value
				// 没有优惠券时的价格
				let price = this.info.price*value
				if(this.yhqId){
					this.uniPrice = price - this.yhPrice
				}else{
					this.uniPrice = this.info.price*value
				}
				console.log('this.info.price',this.info.price)
				console.log('value',value)
				console.log('22222222222222',this.uniPrice)
			},
			formSubmit: function(e) {
				console.log('form发生了submit事件，携带数据为：' + JSON.stringify(e.detail.value))
			    //定义表单规则
			    var rule = [
			        {name:"userName", checkType : "string", checkRule:"1,20",  errorMsg:"姓名不正确"},
					{name:"phone", checkType : "string", checkRule:"11",  errorMsg:"联系电话不正确"},
					{name:"address", checkType : "string", checkRule:"1,50",  errorMsg:"收货地址不能为空"},
			    ];
			    //进行表单检查
			    var formData = e.detail.value;
			    var checkRes = graceChecker.check(formData, rule);
			    if(checkRes){
			        // uni.showToast({title:"验证通过!", icon:"none"});
					// 调用支付接口
					this.getPayment()
			    }else{
			        uni.showToast({ title: graceChecker.error, icon: "none" });
			    }
			},
		},
		//时间戳的处理
		filters: {
			formatDate: function(value) {
				var date = new Date(value*1000);
				var Y = date.getFullYear() + '-';
				var M = (date.getMonth()+1 < 10 ? '0'+(date.getMonth()+1) : date.getMonth()+1) + '-';
				var D = date.getDate() + ' ';
				// var h = date.getHours() + ':';
				// var m = date.getMinutes() + ':';
				// var s = date.getSeconds();
				return Y+M+D;
			}
		},
	}
</script>

<style>
	.container{
		width: 100%;
		background: #f6f6f6;
	}
	
	.swiper{
		height: 100%;
	}
	
	.swiper image{
		width: 100%;
		height: 100%;
	}
	
	.page{
		position: absolute;
		right: 20rpx;
		top: 13rpx;
		background: rgba(0, 0, 0, 0.3);
		font-size: 22rpx;
		padding: 5rpx 17rpx;
		border-radius: 26rpx;
		color: #fff;
	}
	
	.swiperBox{
		height: 480rpx;
	}
	
	.info{
		display: flex;
	}
	
	.infoBox{
		background-color: #fff;
		padding: 20rpx;
		font-size: 26rpx;
		border-bottom: 1px solid #6a8473;
	}
	
	.price{
		color: #6a8473;
		font-weight: 400;
		font-size: 34rpx;
	}
	
	.inventory{
		margin-left: auto;
		color: #979596;
		font-weight: 300;
	}
	
	.name{
		font-weight: 300;
		margin-top: 10rpx;
		font-weight: 30rpx;
	}
	
	.content{
		padding: 20rpx;
		background: #fff;
		margin: 20rpx auto 0;
		border: 1px solid #6a8473;
	}
	
	.iconImg{
		width: 35rpx;
		height: 35rpx;
		margin-right: 5rpx;
		position: relative;
		top: 8rpx;
	}
	
	.content h3{
		font-size: 28rpx;
		padding-left: 4rpx;
		height: 40rpx;
		line-height: 40rpx;
		font-weight: 400;
		margin-bottom: 20rpx;
		color: #6a8473;
	} 
	
	.infoCon{
		font-size: 24rpx;
		line-height: 42rpx;
		font-weight: 300;
	}
	
	.btn{
		background: #6a8473;
		color: #fff;
		width: 88%;
		font-size: 30rpx;
		border-radius: 0;
		position: fixed;
		bottom: 30rpx;
		left: 0;
		right: 0;
		font-weight: 300;
	}
	
	.vue-ref{
		padding-bottom: 0!important;
	}
	
	.popup{
		background: #fff;
		height: 800rpx;
		width: 94.5%;
		padding: 20rpx;
	}
	
	.colse{
		width: 40rpx;
		height: 40rpx;
		float: right;
	}
	
	.yhqcolse{
		width: 40rpx;
		height: 40rpx;
		float: right;
		margin-bottom: 20rpx;
	}
	
	.img-item {
	  width: 100px;
	  height: 100px;
	  margin: 10px;
	}
	
	.shopTop{
		display: flex;
	}
	
	.shopTop image{
		border-radius: 10rpx;
	}
	
	.shopR{
		padding: 20rpx 0;
		width: 450rpx;
	}
	
	.shopPrice{
		margin-top:110rpx;
		display: flex;
	}
	
	.priceItem{
		color: #6a8473;
	}
	
	.shopNum{
		margin-left: auto;
	}
	
	.uni-form-item{
		display: flex;
		font-size: 26rpx;
		border-bottom: 1px solid #ededed;
		padding:20rpx;
	}
	
	.uni-form-item .title{
		width: 130rpx
	}
	
	/* .couponBox{
		margin-left: auto;
	} */
	
	.coupon{
		color: #6a8473;
	}
	
	.Ricon{
		width: 32rpx;
		height: 32rpx;
		position: relative;
		top: 6rpx;
	}
	
	.gmBtn{
		background-color: #6a8473;
		width: 265rpx;
		font-size: 28rpx;
		color: #fff;
		border-radius: 0;
		font-weight: 300;
		
	}
	
	.gmBtn text{
		font-size: 34rpx;
		color: #6a8473;
	}
	
	.uni-btn-v{
		display: flex;
		margin-top: 40rpx;
		position: absolute;
		right: 20rpx;
	}
	
	.uniPrice{
		line-height: 66rpx;
		color: #6a8473;
		font-size: 33rpx;
		margin-right: 40rpx;
	}
	
	.shopRName{
		font-size: 28rpx;
	}
	
	.uni-numbox-btns {
		border: 1px solid #6a8473;
	}
	
	.uni-numbox--text {
		color: #6a8473!important;
	}
	
	
	.uni-numbox__value {
		border: 1px solid #6a8473!important;
		color: #6a8473!important;
	}
	
	.uni-form-item input {
	  color: #6a8473;
	}
	
	.yhqBox{
		background-color: #fff;
		padding: 20rpx;
	}
	
	.couponItem{
		width: 88%;
		display: flex;
		border: 1px solid #ddd;
		border-left: 2px solid #6a8473;
		border-radius: 10rpx;
		padding: 20rpx;
		height: 120rpx;
		box-shadow: 1px 1px 10rpx #ddd;
		background-color: #fff;
		margin: 0 auto 20rpx;
	}
	
	.couponPrice{
		width: 130rpx;
		line-height: 120rpx;
		font-weight: bold;
		color: #6a8473;
	}
	
	.couponInfo{
		font-size: 24rpx;
		line-height: 42rpx;
		color: #949090;
	}
	
	.couponBtn{
		margin-left: auto;
		margin-right: 20rpx;
		border-left: 1px dashed #ddd;
		padding-left: 20rpx;
	}
	
	.couponTxt,.couponlod,.couponlodz{
		font-size: 24rpx;
		background-color: #ddd;
		color: #fff;
		padding: 5rpx 15rpx;
		border-radius: 10rpx;
		margin-top: 38rpx;
	}
	
	.couponlod{
		background-color: #6a8473;
	}
	
	.couponTitle{
		font-weight: bold;
		color: #000;
	}
</style>